package org.android.data;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import org.android.util.XBeanUtils;
import android.annotation.SuppressLint;
import android.database.Cursor;
import android.util.Log;

public class XSqliteUtils {
	
	/**
	 * 用给定的参数填满sql中的问号
	 * @param sql 
	 * @param params
	 * @return
	 * @throws Exception
	 */
	public static String setParamsToSql(String sql,String... params){
		//健壮性 判断参数与问好是否相等
		if(params!=null){
			int count=0;
			for(char c:sql.toCharArray()){
				if(c=='?'){
					count++;
				}
			}
			
			if(count!=params.length){
				try {
					throw new Exception("参数数量与sql的问号数量不匹配~");
				} catch (Exception e) {
					Log.e("setParamsToSql", ""+e);
				}
			}
		}else{
			return sql;
		}
		//开始
		
		for(int i=0;i<params.length;i++){
			sql=sql.replaceFirst("\\?",params[i]);
		}
		return sql;
	}
	@SuppressLint("NewApi")
	/**
	 * 将一条带有有效指针的Currsor里面的数据封装到Bean里 
	 * @param cursor 有效指针的cursor对象
	 * @param BeanClass 目标Bean的Class
	 * @return	Bean
	 * @throws InstantiationException
	 * @throws IllegalAccessException
	 * @throws NoSuchMethodException
	 * @throws IllegalArgumentException
	 * @throws InvocationTargetException
	 */
	public static <T> T parseCursorToBean(Cursor cursor,Class<T> BeanClass) throws InstantiationException, IllegalAccessException, NoSuchMethodException, IllegalArgumentException, InvocationTargetException{
		T t=BeanClass.newInstance();
		Field[] fields=BeanClass.getDeclaredFields();
		
		for(String fieldName:cursor.getColumnNames()){
			
			//对应字段名所在的下标
			int index=cursor.getColumnIndex(fieldName);
			//获取下标所对应的类型
			int type=cursor.getType(index);
			//根据下标所对应的类型 进行取值 赋值
			if(type==Cursor.FIELD_TYPE_STRING){
				XBeanUtils.setBeanValue(t,fieldName,cursor.getString(index));
			}
			if(type==Cursor.FIELD_TYPE_INTEGER){
				XBeanUtils.setBeanValue(t,fieldName,cursor.getInt(index));
			}
			if(type==Cursor.FIELD_TYPE_FLOAT){
				XBeanUtils.setBeanValue(t,fieldName,cursor.getFloat(index));
			}
			if(type==Cursor.FIELD_TYPE_BLOB){
				XBeanUtils.setBeanValue(t,fieldName,cursor.getBlob(index));
			}
			if(type==Cursor.FIELD_TYPE_NULL){
				XBeanUtils.setBeanValue(t,fieldName,null);
			}
		}
		return t;
	}

}
